package com.cqut.forum.controller;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.cqut.forum.entity.Hotpost;
import com.cqut.forum.entity.Post;
import com.cqut.forum.service.IPostService;
import com.cqut.forum.service.impl.UserService;
import com.cqut.forum.util.ConfigProperties;
import com.cqut.forum.util.DateUtil;
import com.cqut.forum.util.DefaultElements;
import com.cqut.forum.util.StringUtil;
@Controller
@RequestMapping(value="/setting")
public class PostController_2 {
	 Logger logger  =  Logger.getLogger(PostController_2. class );
	private IPostService  postService;

	public void setPostService(IPostService postService) {
		this.postService = postService;
	}
	/**
	* @Title: postManage
	* @Description: 返回帖子管理页面  
	* @return String  
	* @author 刘强   
	* @date 2015-5-19 上午11:07:34
	*/ 
	@RequestMapping(value="/postManage.do")
	public String postManage(HttpServletRequest request,HttpServletResponse response){
		return "setting/postManage";
	}
	@RequestMapping(value="/postManageJson.do")
	public void postManageJson(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> root=new HashMap<String,Object>();
		int currentPage = Integer.parseInt(request.getParameter("page"));
		int pageSize    = Integer.parseInt(request.getParameter("rows"));
		String order     = request.getParameter("order")== null?"":request.getParameter("order");		//排序的方式
		String sort     = request.getParameter("sort")== null?"":request.getParameter("sort");
		String title = request.getParameter("title") == null?"":request.getParameter("title");
		String userName=request.getParameter("userName") == null?"":request.getParameter("userName");
		String starTime=request.getParameter("starTime");
		String endTime=request.getParameter("endTime");
		List<Post> list=postService.getPost(title, userName, starTime, endTime, currentPage, pageSize, order, sort);
		int total=postService.getPostTotal(title, userName, starTime, endTime);
		root.put("rows", list);
		root.put("total",total);
		StringUtil.writeToWeb(JSONObject.fromObject(root).toString(), "html", response);

	}
	@RequestMapping(value="/frozenPost.do")
	public void frozenPost(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> root=new HashMap<String,Object>();
		String idsStr=request.getParameter("id");
		Post post=postService.getPost(Long.parseLong(idsStr));
		post.setIsfrozen(1);
		postService.saveOrupdate(post);
		root.put("result", 1);
		StringUtil.writeToWeb(JSONObject.fromObject(root).toString(), "html", response);

	}
	@RequestMapping(value="/thawPost.do")
	public void thawPost(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> root=new HashMap<String,Object>();
		String idsStr=request.getParameter("id");
		Post post=postService.getPost(Long.parseLong(idsStr));
		post.setIsfrozen(0);
		postService.saveOrupdate(post);
		root.put("result", 1);
		StringUtil.writeToWeb(JSONObject.fromObject(root).toString(), "html", response);

	}
	/**
	* @Title: setHotPost_1
	* @Description: 设置热帖1  
	* @return void  
	* @author 刘强   
	* @date 2015-5-19 下午4:29:36
	*/ 
	@RequestMapping(value="/setHotPost_1.do")
	public void setHotPost_1(HttpServletRequest request,HttpServletResponse response){
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;  
		CommonsMultipartFile image = (CommonsMultipartFile) multipartRequest.getFile("file");
		String id=null;
		try {
			id=new String(multipartRequest.getParameter("id").getBytes("ISO8859-1"), "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			logger.error("PostController_2 方法setHotPost_1错误", e1);
		}
		 String realFileName = image.getOriginalFilename();  
		 String uuid=UUID.randomUUID().toString();
	        // 获取路径  
	        String ctxPath = null;
//			ctxPath=this.getClass().getClassLoader().getResource("").getPath()+ "images/";
				ctxPath = request.getSession().getServletContext().getRealPath(  
				        "\\") + "images\\";  
	        // 创建文件  
	        File dirPath = new File(ctxPath);  
	        if (!dirPath.exists()) {  
	            dirPath.mkdir();  
	        }  
	        File uploadFile = new File(ctxPath + uuid+getSuffix(realFileName));  
	        try {
				image.transferTo(uploadFile);
			} catch (Exception e) {
                logger.error("PostController_2方法setHotPost_1",e);
				e.printStackTrace();
			}
	        Hotpost hotpost=new Hotpost();
	        hotpost.setImagePath(getPath(uploadFile.getAbsolutePath()));
	        hotpost.setType(DefaultElements.ZERO);
	        hotpost.setPostId(Long.parseLong(id));
	        hotpost.setData(DateUtil.getCurrentDate());
	        postService.saveHotpost(hotpost);
	        Map<String,Object> root=new HashMap<String,Object>();
	        int result=1;
			root.put("result",result);
		   StringUtil.writeToWeb(JSONObject.fromObject(root).toString(), "html", response);

	}
	/**
	* @Title: setHotPost_2
	* @Description: 设置热帖2 
	* @return void  
	* @author 刘强   
	* @date 2015-5-19 下午5:58:13
	*/ 
	@RequestMapping(value="/setHotPost_2.do")
	public void setHotPost_2(HttpServletRequest request,HttpServletResponse response){
		String idsStr=request.getParameter("id");
		String[] ids=idsStr.split(",");
		for(int i=0;i<ids.length;i++){
			Hotpost hotpost=new Hotpost();
			hotpost.setPostId(Long.parseLong(ids[i]));
			hotpost.setType(DefaultElements.ONE);
			hotpost.setData(DateUtil.getCurrentDate());
			hotpost.setImagePath("");
			postService.saveHotpost(hotpost);
		}
		Map<String,Object> root=new HashMap<String,Object>();
        int result=1;
		root.put("result",result);
		StringUtil.writeToWeb(JSONObject.fromObject(root).toString(), "html", response);

	}
	
	/**
	* @Title: getSuffix
	* @Description: 前缀  
	* @return String  
	* @author 刘强   
	* @date 2015-5-14 下午1:45:30
	*/ 
	private String getSuffix(String str){
		String suffixstr=str.substring(str.lastIndexOf("."));
		return suffixstr;
	}
	/**
	* @Title: getPath
	* @Description: 获取相对路径 
	* @return String  
	* @author 刘强   
	* @date 2015-5-14 下午1:45:46
	*/ 
	private String getPath(String realPath){
		String projectName=ConfigProperties.get("projectName");
		String path=realPath.substring(realPath.indexOf(projectName)+projectName.length()+1);
		path=path.replace("\\", "/");
		return path;
	}
//////////////////////////////////////////////////////////////////热帖设置
	
	/**
	* @Title: hotpostManage
	* @Description: 返回热帖管理页面  
	* @return String  
	* @author 刘强   
	* @date 2015-5-19 下午6:23:20
	*/ 
	@RequestMapping(value="/hotpostManage.do")
	public String hotpostManage(HttpServletRequest request,HttpServletResponse response){
		return "setting/hotpostManage";
	}
	/**
	* @Title: hotpostManageJson
	* @Description: 返回热帖数据  
	* @return void  
	* @author 刘强   
	* @date 2015-5-19 下午6:25:09
	*/ 
	@RequestMapping(value="/hotpostManageJson.do")
	public void hotpostManageJson(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> root=new HashMap<String,Object>();
		int currentPage = Integer.parseInt(request.getParameter("page"));
		int pageSize    = Integer.parseInt(request.getParameter("rows"));
		String order     = request.getParameter("order")== null?"":request.getParameter("order");		//排序的方式
		String sort     = request.getParameter("sort")== null?"":request.getParameter("sort");
		String title = request.getParameter("title") == null?"":request.getParameter("title");
        List<Hotpost> list=postService.getHotPost(title,currentPage, pageSize, order, sort);	
        
        int total=postService.getHotPostTotal(title);
		root.put("rows", list);
		root.put("total",total);
		StringUtil.writeToWeb(JSONObject.fromObject(root).toString(), "html", response);

	}
	/**
	* @Title: delHotpost
	* @Description: 删除热帖  
	* @return void  
	* @author 刘强   
	* @date 2015-5-19 下午6:36:20
	*/ 
	@RequestMapping(value="/delHotpost.do")
	public void delHotpost(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> root=new HashMap<String,Object>();
		String idsStr=request.getParameter("id");
		String[] ids=idsStr.split(",");
		for(int i=0;i<ids.length;i++){
			postService.deleteHotpost(Long.parseLong(ids[0]));
		}
		root.put("result",1);
		StringUtil.writeToWeb(JSONObject.fromObject(root).toString(), "html", response);

	}
}
